package com.lovo.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.lovo.model.Role;
import com.lovo.model.User;
import com.lovo.service.UserService;
import com.lovo.service.impl.UserServiceImpl;
import com.lovo.util.CodeMsg;
import com.lovo.util.JwtUtil;
import com.lovo.util.MyUtils;
import com.lovo.util.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;

@WebServlet(name = "UserServlet",urlPatterns = "/user.do")
public class UserServlet extends HttpServlet {
    UserService us = new UserServiceImpl();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        if(method == null||method.equals("")){
            indexByPage(request,response);
        }else if (method.equalsIgnoreCase("login")){
            login(request,response);
        }else if(method.equalsIgnoreCase("register")){
            register(request,response);
        }else if(method.equalsIgnoreCase("verify")){
            verify(request,response);
        }else if(method.equalsIgnoreCase("deleteUser")){
            deleteUser(request,response);
        }else if(method.equalsIgnoreCase("updateUser")){
            updateUser(request,response);
        }else if(method.equalsIgnoreCase("hasRoles")){
            hasRoles(request,response);
        }else if(method.equalsIgnoreCase("getRoles")){
            getRoles(request,response);
        }else if(method.equalsIgnoreCase("getMenuList")){
            getMenuList(request,response);
        }
    }

    private void getMenuList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String roles = request.getParameter("roles");
        System.out.println("roles = " + roles);
    }

    private void indexByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        int pageNo = 1;
        int pageSize = 10;
        String pageNo1 = request.getParameter("pageNo");
        String pageSize1 = request.getParameter("pageSize");
        if(pageNo1!=null&&!pageNo1.equals("")){
            pageNo = Integer.parseInt(pageNo1);
        }
        if(pageSize1!=null&&!pageSize1.equals("")){
            pageSize = Integer.parseInt(pageSize1);
        }
        String userAccount = request.getParameter("userAccount");
        String userEmail = request.getParameter("userEmail");
        String userTel = request.getParameter("userTel");
        String userName = request.getParameter("userName");
        User user = new User(userAccount,userEmail,userTel,userName);
        PageInfo<User>userPageInfo = us.listByPage(pageNo,pageSize,user);
        out.write(MyUtils.toJSON(userPageInfo));
    }


    private void getRoles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        int userId = Integer.parseInt(request.getParameter("userId"));
        int[] roleIds= us.getRoleIds(userId);
//        String str = Arrays.toString(roleIds);
        out.write(MyUtils.toJSON(roleIds));
    }

    private void hasRoles(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        int userId = Integer.parseInt(request.getParameter("userId"));
        String[] ids = request.getParameter("roleIds").split(",");
        Integer[] roleIds = new Integer[ids.length];
        for (int i = 0; i<ids.length;i++){
            roleIds[i] = Integer.parseInt(ids[i]);
        }
        boolean flag = us.hasRoles(userId,roleIds);
        out.write(String.valueOf(flag));
    }

    private void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        int userId = Integer.parseInt(request.getParameter("userId"));
        String userAccount = request.getParameter("userAccount");
        String userPassword = request.getParameter("userPassword");
        String userTel = request.getParameter("userTel");
        String userEmail = request.getParameter("userEmail");
        String userName = request.getParameter("userName");
        User u = new User(userId,userAccount,userPassword,userTel,userEmail,userName);
        boolean flag = us.updateUser(u);
        out.write(MyUtils.toJSON(flag));
    }

    private void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String userId = request.getParameter("userId");
        boolean flag = us.deleteUser(userId);
        out.write(String.valueOf(flag));
    }

    private void verify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String authHeader = request.getHeader("authorization");
        System.out.println(authHeader);

        //截取前面的Bearer
        String token = authHeader.substring(7);
        // 获取 token 中的 user id
        int userId = 0;
        Result<User> r = null;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (JWTDecodeException j) {
            System.out.println(j.getStackTrace());
            //throw new RuntimeException("访问异常！");
        }

        User user = us.getUserById(userId);

        if (user != null) {
            Boolean verify = JwtUtil.isVerify(token, user);
            if (verify) {
                r = Result.success(user);
            } else {
                r = Result.error(CodeMsg.SERVER_ERROR);
            }

        } else {
            r = Result.error(CodeMsg.SERVER_ERROR);
        }
        out.write(MyUtils.toJSON(r));
    }

    private void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String userAccount = request.getParameter("userAccount");
        String userPassword = request.getParameter("userPassword");
        String userTel = request.getParameter("userTel");
        String userEmail = request.getParameter("userEmail");
        String userName = request.getParameter("userName");
        User u = new User(userAccount,userPassword,userTel,userEmail,userName);
        boolean flag = us.register(u);
        out.write(String.valueOf(flag));

    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String userAccount = request.getParameter("userAccount");
        String userPassword = request.getParameter("userPassword");
        User u = new User();
        u.setUserAccount(userAccount);
        u.setUserPassword(userPassword);
        u = us.login(u);
        Result<User> r = null;
        if (u != null && u.getUserId() !=null) {
            r = Result.success(u);
            String token = JwtUtil.createJWT(6000000, u);
            response.setHeader("Authorization", token);
        } else {
            r = Result.error(CodeMsg.SERVER_ERROR);
        }
        out.write(MyUtils.toJSON(r));
    }


}
